package com.missyoubug.easyjtest.config;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class BrowserOpener implements ApplicationRunner {

    private static final String URL = "http://localhost:8080/test";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (isWindows()) {
            try {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + URL);
            } catch (IOException e) {
                System.err.println("Error opening browser on Windows: " + e.getMessage());
            }
        } else if (isMac()) {
            try {
                Runtime.getRuntime().exec(new String[]{"open", URL});
            } catch (IOException e) {
                System.err.println("Error opening browser on MacOS: " + e.getMessage());
            }
        } else if (isUnix()) {
            try {
                Runtime.getRuntime().exec(new String[]{"xdg-open", URL});
            } catch (IOException e) {
                System.err.println("Error opening browser on Unix/Linux: " + e.getMessage());
            }
        } else {
            System.out.println("Cannot open browser automatically.");
        }
    }

    private boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("win");
    }

    private boolean isMac() {
        return System.getProperty("os.name").toLowerCase().contains("mac");
    }

    private boolean isUnix() {
        return System.getProperty("os.name").toLowerCase().contains("nix") ||
                System.getProperty("os.name").toLowerCase().contains("nux") ||
                System.getProperty("os.name").toLowerCase().contains("aix");
    }
}